package com.wica.view;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.preference.PreferenceManager.OnActivityResultListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;

import com.wica.facebook.FBRocketConnect;
import com.wica.facetube.FaceTubeService;
import com.wica.facetube.R;

public class ListOfMoviesTabs extends TabActivity  implements OnClickListener, OnTabChangeListener {
	// *************** Constants ************** //
	private static final int REQUESTCODE_FACEBOOK = 1;
	// Log constant
	private static final String LOG_TAG = "PTv.ListOfMoviesTabs";
	
	// *************** Attributes ************************* //  
	private TabHost tabHost;
	private FaceTubeService facetube;
	
	// *************** Flags ************************* //
	private ListOfMoviesTabs list;
	
	// *************** Methods **************************** //	
	private Context context;

	@Override
    public void onCreate(Bundle savedInstanceState) {		
        super.onCreate(savedInstanceState);
        if (!internetNetworkAvailable())
        	showDialog(1);
        else {
        	// Inflate layout from layout/tab.xml
        	setContentView(R.layout.tab);
        	// Uncomment the following three lines in order to "facebook connect" a different user and log out from facebook
//        	Editor s = PreferenceManager.getDefaultSharedPreferences(this).edit();
//        	s.remove("userID");
//        	s.commit();
   			Editor s3 = PreferenceManager.getDefaultSharedPreferences(this).edit();
   			String userid = "1";
   			try{
   				BufferedReader inbuff = new BufferedReader(new FileReader(new File("sdcard/wica_files","userID")));
   				userid = inbuff.readLine();
   				Log.v(LOG_TAG, userid);
   			}catch (Exception e) {
   				Log.e(LOG_TAG, e.getMessage()+"");		
   			}
   			s3.putInt("userID",Integer.valueOf(userid));
   			s3.commit();
//        	Log.v(LOG_TAG, ""+PreferenceManager.getDefaultSharedPreferences(this).getInt("userID", -1));
//        	if (PreferenceManager.getDefaultSharedPreferences(this).getInt("userID", -1)==-1||PreferenceManager.getDefaultSharedPreferences(this).getInt("userID", -1)==506){
//            	Log.v(LOG_TAG, "FACEBOOK FROM LISTOFMOVIESTABS "+PreferenceManager.getDefaultSharedPreferences(this).getInt("userID", -1));
//        		/* No user has logged in the app. We ask for login and password
//        		 * Use Facebook library for android. Codecarpet(R)
//        		 * Facebook activity calls onActivityResult method on return */
//        		this.startActivityForResult(new Intent(this,FBRocketConnect.class),REQUESTCODE_FACEBOOK);
//        		/* We are connected through the MobilePersonalTV kApiKey and kApiSecret!!!
//        		 * You don't even need to be register for PersonalTV to get a userID just calling facebookid2UserId
//        		 * Then we store the android preference named userID. We always get a valid userID
//        		 * We do it in onActivityResult method **/
//        	}else{
       			SharedPreferences s2 = PreferenceManager.getDefaultSharedPreferences(this);
       			int movida=s2.getInt("userID",78);
        		Log.v(LOG_TAG, "movida "+movida+"");
        		list = this;
            	GPSConfiguration();
            	tabHost=null;
            	context=this;
        		buildTabs();
//        	}
        }
    }//onCreate method	
	
    protected boolean internetNetworkAvailable() {
        // Local Variables
    	ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] allNetworkInfo = connectivityManager.getAllNetworkInfo();
        int i;
        
        for (i=0;i<allNetworkInfo.length;i++){
        	NetworkInfo networkInfoItem = allNetworkInfo[i];        	
            if (networkInfoItem.isAvailable()){
            	return true;
            }// if
        }// for
		return false;
	}// internetNetworkAvailable method
	
	@Override
	protected void  onActivityResult(int requestCode, int resultCode, Intent data){
		// Local Variables
		Bundle bundle;
        Long facebookID;
        Long userID;
        Editor s; 

       	switch (requestCode) {
       		case REQUESTCODE_FACEBOOK:	     
       			Log.v(LOG_TAG,LOG_TAG+"REQUESTCODE_FACEBOOK");
       			bundle = data.getExtras();
       			facebookID=(Long)bundle.get("userID");
      			facetube = new FaceTubeService();
      			userID = facetube.faceTubeFacebookID2userID(facebookID);
       			s = PreferenceManager.getDefaultSharedPreferences(this).edit();
       			s.putInt("userID",Integer.valueOf(userID.toString()));
       			s.commit();
            	GPSConfiguration();
        		buildTabs();
//        		this.startActivity(new Intent(this, TextLocationDialog.class));
//            	this.startActivity(new Intent(this, MoodDialog.class));
       			break; 
       		case 2:
       			break;
       	}// switch
    }//onActivityResult method
	
	private void buildTabs(){		
        if (tabHost==null){
		// We build tabs
    	tabHost = getTabHost();
    	tabHost	.addTab(tabHost.newTabSpec("Most Viewed")
    			.setIndicator("Most Viewed",getResources().getDrawable(R.drawable.most_viewed))
    			.setContent((new Intent(this, ELMostViewed.class))));
    	tabHost	.addTab(tabHost.newTabSpec("Top Rated")
    			.setIndicator("Top Rated",getResources().getDrawable(R.drawable.top_rated))
    			.setContent((new Intent(this, ELTopRated.class))));
    	tabHost	.addTab(tabHost.newTabSpec("Suggestions")
    			.setIndicator("Suggestions",getResources().getDrawable(R.drawable.suggestions))
    			.setContent((new Intent(this, ELSuggestions.class))));
    	tabHost	.addTab(tabHost.newTabSpec("Search")
    			.setIndicator("Search",getResources().getDrawable(R.drawable.search))
    			.setContent((new Intent(this,ELSearch.class).putExtra("searchString", "__empty"))));
//    	tabHost	.addTab(tabHost.newTabSpec("Tests")
//    			.setIndicator("Tests",getResources().getDrawable(R.drawable.most_viewed))
//    			.setContent((new Intent(this, ListTests.class))));
//    	tabHost	.addTab(tabHost.newTabSpec("Location")
//    			.setIndicator("Location",getResources().getDrawable(R.drawable.tab_location))
//    			.setContent((new Intent(this, Mapping.class))));
//    	tabHost.setCurrentTab(3);

//		tabHost.getChildAt(3).setOnLongClickListener(this);
//		
//		tabHost.getCurrentTabView().setOnLongClickListener(new OnLongClickListener(){
//
//			@Override
//			public boolean onLongClick(View v) {
//				
////				this.startActivityForResult(new Intent(context, DialogActivity.class), 1);
//				return true;
//			}    		
//    	});
    	
    	
//		tabHost.setCurrentTab(3);
//		tabHost.getCurrentTabView().setOnClickListener(this);
		tabHost.setCurrentTab(0);

		}
	}// build method	
    
	protected Dialog onCreateDialog(int id) {
    	return new AlertDialog.Builder(this)
        		.setIcon(R.drawable.stat_sample)
        		.setTitle("No Internet connection was found")
                .setMessage("You need an internet connection in order to use the application")                
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	finish();  
                    }// onclick method
                })
                .create();
    }//onCreateDialog method
	
	@Override
	public void onTabChanged(String tabId) {
		if (tabId.compareTo("Search")==0){
			tabHost.getCurrentTabView().setOnClickListener(this);
			this.startActivityForResult(new Intent(context, DialogActivity.class), 1);
		}				
	}//onTabChanged method
	
	/** By overriding onConfigurationChanged method we avoid recreation when orientation changes.
	 *  Check Android manifest for more details
	 *  
	 *  {@inheritDoc}
	 **/
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    	super.onConfigurationChanged(newConfig);
	}//onConfigurationChanged method
	private LocationListener locationListener;
	private LocationManager locationManager;
	private Location location;

	private void GPSConfiguration() {
		locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
            	Log.v(LOG_TAG, "onlocationchanged");
                location = locationManager.getLastKnownLocation("gps");
            	Editor s = PreferenceManager.getDefaultSharedPreferences(list).edit();
            	s.putFloat("latitude", new Double(location.getLatitude()).floatValue());
            	s.putFloat("longitude", new Double(location.getLongitude()).floatValue());
            	s.putFloat("altitude", new Double(location.getAltitude()).floatValue());
            	s.putFloat("speed", new Float(location.getSpeed()).floatValue());
            	s.commit();
            	locationManager.removeUpdates(locationListener);
            }
            @Override
            public void onProviderDisabled(String provider) {
            }
            @Override
            public void onProviderEnabled(String provider) {
            }
            @Override
            public void onStatusChanged(String provider, int status,Bundle extras) {
            }
        };
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, locationListener);        
        location = locationManager.getLastKnownLocation("gps");        
    	Log.v(LOG_TAG, "GPSConfiguration");

        if(location != null){
        	Editor s = PreferenceManager.getDefaultSharedPreferences(this).edit();
        	s.putFloat("latitude", new Double(location.getLatitude()).floatValue());
        	s.putFloat("longitude", new Double(location.getLongitude()).floatValue());
        	s.putFloat("altitude", new Double(location.getAltitude()).floatValue());
        	s.putFloat("speed", new Float(location.getSpeed()).floatValue());
        	s.commit();
        }    
	}// GPSConfiguration method	

	@Override
	public void onClick(View v) {		
		Log.v(LOG_TAG, "clickeado search");
		tabHost.setCurrentTab(3);
		tabHost.getCurrentTabView().getContext();
		
//		intent.putExtra("searchString", "__empty")
		this.startActivityForResult(new Intent(tabHost.getCurrentTabView().getContext(), DialogActivity.class), 2);
//		this.startActivityFromChild(child, new Intent(tabHost.getCurrentTabView().getContext(), DialogActivity.class), 1)
//		Intent intent = new Intent(tabHost.getCurrentTabView().getContext(), ELSearch.class);
//		intent.putExtra("searchString", "__empty");
//		this.startActivity(intent);
	}	

}//ListOfMoviesTabs class